package jmine.tec.script.impl.velocity.repository;

import static jmine.tec.script.impl.velocity.VelocityLanguageIdentifier.VELOCITY;
import jmine.tec.script.impl.velocity.VelocityEngineBean;
import jmine.tec.script.impl.velocity.VelocityScriptDriver;
import jmine.tec.script.impl.velocity.VelocityScriptExecutor;
import jmine.tec.script.persistent.repository.BaseScriptLoader;
import jmine.tec.script.persistent.repository.ScriptLanguageBuilder;
import jmine.tec.script.persistent.repository.TransientScriptRepository;

/**
 * Classe utilitária para configurar um TransientScriptRepository com suporte adequado a execução de scripts Velocity.
 * 
 * @author lundberg
 */
public final class VelocitySupport {

    private static final String VM_TYPE = "SCRIPT-VM";

    /**
     * Construtor vazio
     */
    private VelocitySupport() {
        // OK
    }

    /**
     * Adiciona suporte a execução de scripts velocity.
     * 
     * @param repository
     */
    public static void addTo(TransientScriptRepository repository) {
        addLanguage(repository);
        addLoader(repository);
        addExecutor(repository);
    }

    /**
     * @param repository
     */
    private static void addExecutor(TransientScriptRepository repository) {
        VelocityScriptExecutor velocityExecutor = new VelocityScriptExecutor();
        VelocityEngineBean velocityEngine = new VelocityEngineBean();
        try {
            velocityEngine.afterPropertiesSet();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        velocityExecutor.setVelocityBean(velocityEngine);
        repository.addExecutor(velocityExecutor);
    }

    /**
     * @param repository
     */
    private static void addLoader(TransientScriptRepository repository) {
        repository.addLoader(new BaseScriptLoader(VM_TYPE, new VelocityScriptDriver()));
    }

    /**
     * @param repository
     */
    private static void addLanguage(TransientScriptRepository repository) {
        ScriptLanguageBuilder velocity = ScriptLanguageBuilder.aLanguage();
        velocity = velocity.identifiedBy(VELOCITY).comMnemonico("VELOCITY").comAbreviacao("VM").executadoPor(VelocityScriptExecutor.class);
        repository.addLanguage(velocity.build());
    }
}
